package com.item.interceptors;

import com.item.pojo.Result;
import com.item.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            // 验证 JWT Token 的有效性
            Map<String, Object> claims = JwtUtil.parseToken(token);
            // 如果验证通过，则放行请求
            System.out.println("放行成功");
            return true;
        } catch (Exception e) {
            // 如果发生异常，则拦截请求
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            System.out.println("Token验证失败或已过期");
            response.getWriter().write("Token验证失败或已过期");
            return false;
        }
    }
}
